<template>
  <a-drawer width="35%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules">
      <a-form-model-item label="活动" prop="activityId" >
        <a-select placeholder="请选择活动" v-model="form.activityId" :filter-option="searchOption" showSearch>
          <a-select-option v-for="(d, index) in activityList" :key="index" :value="d.id" >{{ d.title }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="地址名称" prop="name" >
        <div class="map-search">
          <a-input v-model="form.name" placeholder="请输入地址名称" />
          <a-button @click="searchAddress(form.name)" type="primary">搜索</a-button>
        </div>
        <a-row>
          <a-col :span="12">
            <a-form-item label="经度" prop="longitude">
              <a-input style="width: 200px" disabled v-model="form.lng"></a-input> </a-form-item
            ></a-col>
          <a-col :span="12">
            <a-form-item label="纬度" prop="latitude">
              <a-input style="width: 200px" disabled v-model="form.lat"></a-input> </a-form-item
            ></a-col>
        </a-row>
        <a-form-item>
          <div class="map-box">
            <div class="map" ref="map" id="map" style="height: 300px" />
          </div>
        </a-form-item>
      </a-form-model-item>
      <a-form-model-item label="详细地址" prop="address" >
        <a-input v-model="form.address" placeholder="请输入活动地址" />
      </a-form-model-item>
      <a-form-model-item label="状态" prop="status" >
        <a-select placeholder="请选择状态" v-model="form.status">
          <a-select-option v-for="(d, index) in statusOptions" :key="index" :value="d.value" >{{ d.label }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>
  import { getActivityAddress, addActivityAddress, updateActivityAddress } from '@/api/system/activityAddress'

  export default {
    name: 'CreateForm',
    props: {
        statusOptions: {
            type: Array,
            required: true
          }
        ,activityList: {
            type: Array,
            required: true
          }
    },
    components: {
    },
    data () {
      return {
        submitLoading: false,
        formTitle: '',
        // 表单参数
        form: {
            id: undefined,
            activityId: undefined,
            address: undefined,
            lat: undefined,
            lng: undefined,
            status: '0',
            delFlag: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined
        },
        searchValue: '', //地图搜索
        formMap:{
          longitude:'',
          latitude:'',
        },
        dataMapItem:undefined,
        // 1增加,2修改
        formType: 1,
        open: false,
        markerLayer: null,
        searchEr:null,
        map: null,
        geocoder: null,
        rules: {
          activityId: [
            { required: true, message: '请选择活动', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '地址名称', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '请输入详细地址', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'blur' }
          ],
          lat: [
            { required: true, message: '请输入纬度', trigger: 'blur' }
          ],
          lng: [
            { required: true, message: '请输入经度', trigger: 'blur' }
          ]
        }
      }
    },
    filters: {
    },
    created () {

    },
    updated() {

    },
    computed: {
    },
    watch: {
      open (val) {
        if (val ) {
          if (!this.map){
            setTimeout( ()=>{
              this.initMap();
            },0)
          }else {
            if (this.form.lat&&this.form.lng){
              this.setMarker();
              this.setCenter();
            }
          }
        }
      }
    },
    mounted () {
      //this.initMap();
    },
    methods: {
      searchOption(input,option){
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      // 地图
      initMap() {
        this.dataMapItem = this.$refs['map'];
        console.log(this.$refs)
        console.log(this.$refs['map'])
        // 搜索类
        this.searchEr = new window.TMap.service.Search({ pageSize: 10 });
        // 地图主类
        this.map = new window.TMap.Map(this.$refs.map, {
          backgroundColor: '#f7f7f7',
          mapStyleId: 'style1',
          zoom: 16,
          mapTypeControlOptions: {
            mapTypeIds: [],
          },
          draggableCursor: 'crosshair',
          center: new window.TMap.LatLng(36.665435, 117.072781),
        });
        // 图层类
        this.markerLayer = new window.TMap.MultiMarker({
          map: this.map,
          geometries: [],
        });

        this.geocoder = new window.TMap.service.Geocoder();
        // 地址逆解析
        if (this.form.lat&&this.form.lng){
          this.setMarker();
          this.setCenter();
        }
        this.map.on('click', (e) => {
          this.form.lng = e.latLng.getLng(); // 经度
          this.form.lat = e.latLng.getLat(); // 纬度
          this.setMarker();
          this.getAddressFormat();
        });
      },
      setCenter(){
        this.map.setCenter(new window.TMap.LatLng(this.form.lat, this.form.lng));
      },
      setMarker(){
        const latlng = new window.TMap.LatLng(this.form.lat, this.form.lng);
        this.markerLayer.setGeometries([]);
        let geometries = this.markerLayer.getGeometries();
        geometries.push({
          id: '-1',
          position: latlng,
        });
        this.markerLayer.updateGeometries(geometries);
      },
      // 地图搜索
      searchAddress(keyword = '') {
        if (!keyword) return;
        this.markerLayer.setGeometries([]);
        this.searchEr
          .searchRectangle({
            keyword,
            bounds: this.map.getBounds(),
          })
          .then((result) => {
            const { location = {} } = result.data[0] || {};
            const { lat = 36.665435, lng = 117.072781 } = location;
            this.map.setCenter(new window.TMap.LatLng(lat, lng));
            result.data.forEach((item, index) => {
              let geometries = this.markerLayer.getGeometries();
              // 点标注数据数组
              geometries.push({
                id: String(index),
                position: item.location,
              });
              // 绘制地点标注
              this.markerLayer.updateGeometries(geometries);
            });
          });
      },
      getAddressFormat() {
        const { lng, lat } = this.form;
        this.geocoder.getAddress({
            location: new window.TMap.LatLng(lat, lng),
          })
          .then((res) => {
            const {
              formatted_addresses: { recommend = '',standard_address = '' },
            } = res.result || {};
            this.form.name = recommend;
            this.form.address = standard_address;
          });
      },
      onClose () {
        this.open = false
      },
      // 取消按钮
      cancel () {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset () {
        this.formType = 1
        this.form = {
            id: undefined,
            activityId: undefined,
            name:"鼎峰中心",
            address: "山东省济南市历下区二环东路",
            lat: '36.665435',
            lng: '117.072781',
            status: '0',
            delFlag: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined
        }
      },
      /** 新增按钮操作 */
      handleAdd (row) {
        this.reset()
        this.formType = 1
        this.open = true
        this.formTitle = '添加'
        // if (!this.dataMapItem){
        //   setTimeout(() => {
        //     this.initMap();
        //   },2000)
        // }
      },
      /** 修改按钮操作 */
      handleUpdate (row, ids) {
        this.reset()
        this.formType = 2
        const id = row ? row.id : ids
        getActivityAddress(id).then(response => {
          this.form = response.data
          this.open = true
          this.formTitle = '修改'
          if (this.map){
            if (this.form.lat&&this.form.lng){
              this.setMarker();
              this.setCenter();
            }
          }
          // if (!this.dataMapItem){
          //   setTimeout(() => {
          //     this.initMap();
          //   },2000)
          // }
        })

      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.submitLoading = true
            if (this.form.id !== undefined && this.form.id !== null) {
              updateActivityAddress(this.form).then(response => {
                this.$message.success('修改成功',3)
                this.open = false
                this.$emit('ok')
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addActivityAddress(this.form).then(response => {
                this.$message.success('新增成功',3)
                this.open = false
                this.$emit('ok')
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            return false
          }
        })
      }
    }
  }
</script>
